//
//  CollegeDetailViewController.m
//  Arts1
//  高校详情页面
//  Created by lanou on 15/8/29.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "CollegeDetailViewController.h"
#import "CollegeDetailHeadView.h"

#import "CollegeStateCollectionViewController.h"
#import "CollegeRecruitCollectionViewController.h"
#import "CollegeGradeCollectionViewController.h"
#import "CollegeExamnitionCollectionViewController.h"

#import "SCHDStateViewController.h"
#import "SCHDGrateViewController.h"
#import "SCHDRecruitViewController.h"
#import "SCHDExamnitionViewController.h"


#import "CollegeHeadView.h"
#import "AllHeader.h"

#import "SSDetailModel.h"

// 微信分享
#import "ShareViewController.h"

// 高校详情接口
#define kUrl @"http://arts1.dlab.com.cn/app/spaceinfo"

// 获取关注状态接口
#define gfsURL @"http://arts1.dlab.com.cn/app/getfollowstatus"

// 添加或取消关注接口
#define sfURL @"http://arts1.dlab.com.cn/app/setfollow"


@interface CollegeDetailViewController ()

// 最新动态
@property (nonatomic, strong) CollegeStateCollectionViewController *stateCVC;

// 招生简章
@property (nonatomic, strong) CollegeRecruitCollectionViewController *recruitVC;

// 成绩查询
@property (nonatomic, strong) CollegeGradeCollectionViewController *gradeVC;

// 历年考题
@property (nonatomic, strong) CollegeExamnitionCollectionViewController *examinationVC;


// 院校名称和图像视图
@property (nonatomic, strong) CollegeHeadView *headView;

// 院校信息列表
@property (nonatomic, strong) UITableView *mainTableview;

// 自定义navigationbar
@property (nonatomic, strong) CollegeDetailHeadView *navigationview;

// 纪录上一次现实的视图的 UIViewController
@property (nonatomic, strong) UICollectionViewController *lastVC;

// 高校详情model类
@property (nonatomic, strong) SSDetailModel *school;

// 分享选项页面
@property (nonatomic, strong) ShareViewController *shareVC;


@end

@implementation CollegeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = kCustomColor(250, 250, 250, 1);
    self.view.backgroundColor = kBackgroundColor;
    
    // Do any additional setup after loading the view.
    [self createShareView];
    [self createStateView];
    [self requestData];
    [self createHeadView];
     _lastVC = _stateCVC;
}

//请求数据
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *pardic = @{@"id":_ID};
    
    [manage GET:kUrl parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             // 请求返回的状态，当status = 1 时有数据
              NSInteger status = [dic[@"status"] integerValue];
             if (status == 1) {
                 NSDictionary *dict = dic[@"data"];
                 // 将数据装换成model类
                  _school = [[SSDetailModel alloc] init];
                 [_school setValuesForKeysWithDictionary:dict];
             }
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 _headView.school = _school;
                 _navigationview.school = _school;
                              });
             NSLog(@"高校详情页面 ===数据请求--%@", dic);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];

}


- (void)createHeadView
{
    // 院校名称和图像视图
    _headView = [[CollegeHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , 178)];
    [_headView.attentionBTN addTarget:self action:@selector(followClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_headView];
    
    // 自定义UINavigationBar
    _navigationview = [[CollegeDetailHeadView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
    
    // 返回按钮点击事件
    [_navigationview.backButton addTarget:self action:@selector(backBefore) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 分享按钮点击事件
    [_navigationview.shareBTN addTarget:self action:@selector(shareMessage:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_navigationview];
    
    // 动态、简章、成绩、考题的点击事件的回调block
    __weak CollegeDetailViewController *wCollegeDVC = self;
    _headView.changeviewblock = ^(NSInteger index){
             NSLog(@"_lastVC : %@ ",wCollegeDVC.lastVC);
        
        //  将上一个视图移除
        [wCollegeDVC.lastVC.collectionView removeFromSuperview];
        //  展示被点击的按钮对应的视图
        switch (index) {
            case 0:{
                [wCollegeDVC createStateView];
                wCollegeDVC.lastVC = wCollegeDVC.stateCVC;
            }
                break;
            case 1:{
                [wCollegeDVC createRecruitview];
                wCollegeDVC.lastVC = wCollegeDVC.recruitVC;
            }
                break;
            case 2:{
                [wCollegeDVC createGrateview];
                wCollegeDVC.lastVC = wCollegeDVC.gradeVC;
            }
                break;
            case 3:{
               [wCollegeDVC createExaminationView];
                wCollegeDVC.lastVC = wCollegeDVC.examinationVC;
            }
                break;
            default:
                break;
        }
    };
    
}

// 创建分享选项卡
- (void)createShareView{
    _shareVC = [[ShareViewController alloc] init];
    [self.view addSubview:_shareVC.view];
    _shareVC.view.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
}

// 返回上一级界面
- (void)backBefore{
    [self.navigationController popViewControllerAnimated:YES];
    _navigationview.hidden = YES;
}

// 分享
- (void)shareMessage:(UIButton *)btn{
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _shareVC.view.frame = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
    }];
}



// 创建最新动态的列表页面
- (void)createStateView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10,10, 10);
    layout.minimumInteritemSpacing = 10;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _stateCVC = [[CollegeStateCollectionViewController alloc] initWithCollectionViewLayout:layout];
    _stateCVC.spaceId = _ID;
    [self.view addSubview:_stateCVC.view];
    _stateCVC.collectionView.frame = CGRectMake(0, 178, SCREEN_WIDTH, SCREEN_HEIGHT - 213);
    
     __weak CollegeDetailViewController *wCollegeDVC = self;
    _stateCVC.schoolstateBlock = ^(NSString *str){
        SCHDStateViewController *stateDVC = [[SCHDStateViewController alloc] init];
        stateDVC.ID = str;
        [wCollegeDVC.navigationController pushViewController:stateDVC animated:YES];
    };

}

// 创建招生简章的列表页面
- (void)createRecruitview{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10,10, 10);
    layout.minimumInteritemSpacing = 10;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _recruitVC = [[CollegeRecruitCollectionViewController alloc] initWithCollectionViewLayout:layout];
     _recruitVC.spaceId = _school.Id;
    [self.view addSubview:_recruitVC.collectionView];
    _recruitVC.collectionView.frame = CGRectMake(0, 178, SCREEN_WIDTH, SCREEN_HEIGHT - 213);
    // 点击进入第二层详情页面
   __weak CollegeDetailViewController *wCellegeDVC = self;
    _recruitVC.enterSecondDetaileBlock = ^void(NSString *str){
        SCHDRecruitViewController *secondDVC = [[SCHDRecruitViewController alloc] init];
        secondDVC.ID = str;
    [wCellegeDVC.navigationController pushViewController:secondDVC animated:YES];
    };
}

// 创建成绩查询的列表页面
- (void)createGrateview{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10,10, 10);
    layout.minimumInteritemSpacing= 10;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _gradeVC = [[CollegeGradeCollectionViewController alloc] initWithCollectionViewLayout:layout];
    _gradeVC.spaceId = _school.Id;
    [self.view addSubview:_gradeVC.collectionView];
    _gradeVC.collectionView.frame = CGRectMake(0, 178, SCREEN_WIDTH, SCREEN_HEIGHT - 213);
    
       __weak CollegeDetailViewController *wCellegeDVC = self;
    _gradeVC.schoolgrateBlock = ^(NSString *str){
        SCHDGrateViewController *grateDVC = [[SCHDGrateViewController alloc] init];
        grateDVC.ID = str;
        [wCellegeDVC.navigationController pushViewController:grateDVC animated:YES];
    };
    
}

// 创建历年考题的列表页面
- (void)createExaminationView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10,10, 10);
    layout.minimumInteritemSpacing = 10;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _examinationVC = [[CollegeExamnitionCollectionViewController alloc] initWithCollectionViewLayout:layout];
      _examinationVC.spaceId = _school.Id;
    [self.view addSubview:_examinationVC.collectionView];
    _examinationVC.collectionView.frame = CGRectMake(0, 178, SCREEN_WIDTH, SCREEN_HEIGHT - 213);
    
     __weak CollegeDetailViewController *wCellegeDVC = self;
    _examinationVC.schoolExamBlock = ^(NSString *str){
        SCHDExamnitionViewController *examDVC = [[SCHDExamnitionViewController alloc] init];
        examDVC.ID = str;
        [wCellegeDVC.navigationController pushViewController:examDVC animated:YES];
    
    };
}

// 关注点击事件
- (void)followClick:(UIButton *)btn{
    [self requestGetFollow];
}


// 获取关注状态
- (void)requestGetFollow
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    //请求参数
    NSDictionary *pardic = @{@"type":@"space",@"uid":userDic[@"data"][@"uid"],@"followuid":_ID};
    
    [manage POST:gfsURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         //返回的状态
         int index = [dic[@"status"] intValue];
         //  1是已关注，0是未关注
         switch (index) {
             case 0:
                 [self requestSetFollow:0];
                 break;
             case 1:
                 [self requestSetFollow:1];
                 break;
             default:
                 break;
         }
         NSLog(@" 高校关注状态 %@",dic);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
    
}


// 添加或取消关注
- (void)requestSetFollow:(NSInteger)index
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    //  添加和取消关注的请求参数不一样
    NSString *action = nil;
    
    switch (index) {
        case 0:
            // 未关注，此时需要添加
            action = @"add";
            break;
        case 1:
            // 已关注，此时应该取消
            action = @"cancel";
            break;
        default:
            break;
    }
    
    //请求参数
    NSDictionary *pardic = @{@"type":@"space",@"uid":userDic[@"data"][@"uid"],@"userId":_ID,@"key":userDic[@"data"][@"key"],@"act":action};
    
    [manage POST:sfURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         //记录请求返回结果
         NSString *statusStr = nil;
         //返回的状态
         int status = [dic[@"status"] intValue];
         switch (status) {
             case 1:
                 statusStr = @"操作成功";
                 break;
             case 0:
                 statusStr = @"用户名或密码错误";
                 break;
             case -1:
                 statusStr = @"参数不正确";
                 break;
             case -2:
                 statusStr = @"获取失败";
                 break;
             case -3:
                 statusStr = @"不能关注自己";
                 break;
             case -4:
                 statusStr = @"已经关注，不需要再次关注";
                 break;
                 
             default:
                 break;
         }
         
         if (statusStr)
         {
             //信息提示框
             [MBProgressHUD show:statusStr icon:nil view:self.view];
         }
         
         NSLog(@" 高校添加或取消关注状态 %@",dic);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
